//
//  Bed+CRUD.m
//  PlotMate
//
//  Created by Brian Boyle on 04/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "Bed+CRUD.h"

@implementation Bed (CRUD)

+(Bed *)createBed:(Bed *)bed inPlot:(Plot *)plot withContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Bed"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", bed.name];
    
    NSError *error;
    NSArray *existingBeds = [context executeFetchRequest:request error:&error];
    
    if([existingBeds count] == 0){
        Bed *newBed = [NSEntityDescription insertNewObjectForEntityForName:@"Bed" inManagedObjectContext:context];
        newBed.name = bed.name;
        newBed.size1 = bed.size1;
        newBed.size2 = bed.size2;
        newBed.plot = plot;
        return newBed;
    }else{
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"A Bed named %@ already exists, please choose a different name", bed.name] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [errorAlert show];
        return nil;    
    }
}


+(Bed *)createBedFromTempBed:(TempBed *)bed withContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Bed"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", bed.name];
    
    NSError *error;
    NSArray *existingBeds = [context executeFetchRequest:request error:&error];
    
    if([existingBeds count] == 0){
        Bed *newBed = [NSEntityDescription insertNewObjectForEntityForName:@"Bed" inManagedObjectContext:context];
        newBed.name = bed.name;
        newBed.size1 = bed.size1;
        newBed.size2 = bed.size2;
        return newBed;
    }else{
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"A Bed named %@ already exists, please choose a different name", bed.name] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [errorAlert show];
        return nil;    
    }
}

+(Bed *)selectBedWithName:(NSString *)name inPlot:(NSString *)plotName withContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Bed"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@ AND plot.name = %@", name, plotName];
    
    NSError *error;
    NSArray *existingBeds = [context executeFetchRequest:request error:&error];
    
    return [existingBeds lastObject];
}

@end
